const fs = require('fs-extra');
const path = require('path');

const merge = async (ctx, next) => {
  const {
    file_name
  } = ctx.request.body;
  const file_name_list = file_name.split('.');
  file_name_list.pop();

  const chunkDir = path.join(__dirname, `../public/${file_name_list.join(".")}`);
  const filePath = path.join(__dirname, `../target/${file_name}`); // 存放于目标文件夹下
  console.log(chunkDir)

  try {
    if (fs.existsSync(chunkDir)) {
      const chunkPaths = await fs.readdir(chunkDir);

      await fs.writeFile(filePath, "");

      // 根据切片下标进行排序
      // 否则直接读取目录的获得的顺序可能会错乱
      chunkPaths.sort((ab, cb) => {
        return ab.split("_")[0] - cb.split("_")[0];
      });

      for (const chunkPath of chunkPaths) {
        fs.appendFileSync(filePath, fs.readFileSync(`${chunkDir}/${chunkPath}`));
        fs.unlinkSync(`${chunkDir}/${chunkPath}`); // 释放服务器上切片资源
      }

      fs.rmdirSync(chunkDir); // 合并后删除保存切片的目录
      ctx.body = ctx.request.body;
    } else {
      ctx.body = { status: 200, desc: "文件夹不存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = error;
  }
}

module.exports = merge;